package cn.xshi.common.request;
import cn.xshi.common.base.BaseResult;
import cn.xshi.common.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import cn.xshi.common.util.DecryptUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Desc 重写参数Body体获取
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
    //参数字节数组
    private String requestBody;

    //Http请求对象
    private HttpServletRequest request;

    /**
     *
     * @param request
     * @throws IOException
     */
    public RequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.request = request;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }catch (IOException e) {
                    log.error("RequestWrapper close inputStream is error.{}",e);
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                }catch (IOException e) {
                   log.error("RequestWrapper close bufferedReader is error.{}",e);
                }
            }
            requestBody = stringBuilder.toString();
//            buildParams(requestBody);
        }
    }

    /**
     *
     * @return
     * @throws IOException
     */
    @Override
    public ServletInputStream getInputStream(){
        String encryptBody = null;
        if(!StringUtil.isEmpty(requestBody)){
            try {
                BaseResult baseResult = DecryptUtils.decrypt(requestBody);
                if(baseResult.getSuccess()){
                    encryptBody = ""+baseResult.getData();
                }
            }catch (Exception e){
                log.error("解析解密流异常：{}",e);
            }
        }
        //解密后明文继续传入至控制层
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(null != encryptBody ?encryptBody.getBytes():null);
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
        return servletInputStream;

    }

//    /**
//     * @return
//     * @throws IOException
//     */
//    @Override
//    public ServletInputStream getInputStream() throws IOException {
//        if (null == this.requestBody) {
//            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//            IOUtils.copy(request.getInputStream(), byteArrayOutputStream);
//            this.requestBody = byteArrayOutputStream.toByteArray();
//        }
//
//        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(requestBody);
//        return new ServletInputStream() {
//
//            @Override
//            public boolean isFinished() {
//                return false;
//            }
//
//            @Override
//            public boolean isReady() {
//                return false;
//            }
//
//            @Override
//            public void setReadListener(ReadListener listener) {
//
//            }
//
//            @Override
//            public int read() {
//                return byteArrayInputStream.read();
//            }
//        };
//    }

    /**
     *
     * @return
     */
    public String getRequestBody() {
        return requestBody;
    }

    /**
     *
     * @return
     * @throws IOException
     */
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    /**
     *
     * @param requestBody
     * @return
     */
    private Map<String, String[]> buildParams(String requestBody) {
        Map<String, String[]> map = new HashMap<>();
        Map<String, String> params = JSONObject.parseObject(requestBody, new TypeReference<Map<String, String>>() {});
        for (String key : params.keySet()) {
            map.put(key, new String[]{params.get(key)});
        }
        return map;
    }
}